package interview202234.interview001;

/**
 * 题目1，前缀和
 */
public class Code01_PreSum {
    //预处理最简单的情况：
    //通过预处理前缀和，来搞定范围累加和的查询
    public static class RangeSum1 {
        private int[] arr;

        public RangeSum1(int[] array) {
            arr = array;
        }

        public int rangeSum(int L, int R) {
            int sum = 0;
            for (int i = L; i <= R; i++) {
                sum += arr[i];
            }
            return sum;
        }

    }

    public static class RangeSum2 {
        private int[] preSum;

        public RangeSum2(int[] array) {
            int N = array.length;
            preSum = new int[N];
            preSum[0] = array[0];
            for (int i = 1; i < N; i++) {
                preSum[i] = preSum[i - 1] + array[i];
            }
        }

        public int rangeSum(int L, int R) {
            return L == 0 ? preSum[R] : preSum[R] - preSum[L - 1];
        }

    }

    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        RangeSum2 s = new RangeSum2(arr);
        int rst  =  s.rangeSum(0, arr.length - 1);
        System.out.println(rst);
    }
}
